/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
html={

  /**
 * @function getSelect
 *
 * @param arr, array of (value=>content) or (key=>value,key=>content)
 * @param pick, specify keys from arr array( value, content ) or array(value => keyName, text => keyName )
 * @param attr, array of attributes for select element
 * @param selected, if value is specified in pick array then it should bi one of those values, and if not then specify which row to be selected counting as the arr object
 *
 * @return HTMLSelectElement
 *
 * @example
 * from array(array(1,2,3,4)) as arr and array(3,2) as pick you'll get
 * tag select with one option <option value='4'>3</option>
 * if pick is {"value":1,"text":0} you get <option value='2'>1</option>
 * pick {"value":[1," ? ",0],"text":[3," - ", 2]} you get <option value='2 ? 1'>4 - 3</option>
 */
  getSelect:function(arr, pick,attr,selected){
    var select = this.simpleTag('select', null, attr),keys = [],i,j,key,value,text,tmp_attr;
    for(i in arr){
      keys.push(i);
    }
    keys.sort();
    if(typeof(arr)==typeof(new Object()) || typeof(arr)==typeof(new Array())){
      if(pick!= null && (typeof(pick)==typeof(new Object()) || typeof(pick)==typeof(new Array()))){
        for(key in keys){
          i=keys[key];
          if(!isFinite(i)) continue;
          value = i;
          text = "";
          if(pick["value"]!=null){
            if(typeof(pick["value"])==typeof("")){
              value = arr[i][pick["value"]];
            }else{

              for(j in pick['value']){
                if(arr[i][pick["value"][j]]!=null){
                  value += arr[i][pick["value"][j]];
                }else{
                  value += pick["value"][j];
                }

              }
            }

          }else if(pick["value"] === null){
            value = i;
          }else{
            if(arr[i][pick[0]]!=null){
              value = arr[i][pick[0]];

            }
          }

          if(pick["text"]!=null){
            if(typeof(pick["text"])==typeof("")){
              text = arr[i][pick["text"]];
            }else{

              for(j in pick['text']){

                if(arr[i][pick["text"][j]]!=null){
                  text += arr[i][pick["text"][j]];
                }else{
                  text += pick["text"][j];
                }
              }
            }

          }else if(pick["text"] === null){
            text = 1*i+1;
          }else{
            if(arr[i][pick[1]]!=null){
              text = arr[i][pick[1]];

            }
          }
          tmp_attr = {value:value};
          if(value==selected){
            tmp_attr['selected'] = "selected";
          }
          select.appendChild(this.simpleTag('option', text, tmp_attr));
        }
      }else{
        for(i in arr){
          tmp_attr = {value:i};
          if(i==selected){
            tmp_attr['selected'] = "selected";
          }
          select.appendChild(this.simpleTag('option', arr[i], tmp_attr));
        }
      }
    }
    return select;
  },
  getNumberInput: function(arr){
    var elem = this.simpleTag('input',null,arr);
    var onChange = 'html.validateInput(this); '+elem.getAttribute('onchange');
    var onKeyPress = 'html.validateLiczba(event,this); '+elem.getAttribute('onkeypress');
    elem.setAttribute('onkeypress', onKeyPress);
    elem.setAttribute('onchange', onChange);
    elem.setAttribute('type', 'text');
    return elem;
  },
  toString:function(){var tmp=document.createElement('div');tmp.appendChild(this);return tmp.innerHTML;},
  /*
   * @function simpleTag
   * 
   * @return Element
   */
  simpleTag: function(tag,content,attr){
    var t='',key;
    if(typeof(tag)=='string'){
      t=document.createElement(tag);
      if(is_array(attr)){
        for(key in attr){
          t.setAttribute(key, attr[key]);
        }
      }
      t.append = function(e){
        var l,i,tmpDiv,n;
        if(e instanceof Node){
          this.appendChild(e);
        }else if((e instanceof Array || e instanceof HTMLCollection || e instanceof NodeList || (typeof(jQuery) == "function" && e instanceof jQuery))){
          l = e.length;
          i=0;
          while(i<e.length){
            this.append(e[i]);
            if(l<=e.length){
              i++;
            }
          }
        }else if(e!=null){
          tmpDiv = document.createElement("div");
          tmpDiv.innerHTML = e;
          n = tmpDiv.childNodes;
          if(n.length<1){n = document.createTextNode(e);}
          this.append(n);
          delete n;
          delete tmpDiv;
        }
        return this;
      }
      
      if(content!=null){
        t.append(content);
      }
    }else if(tag===null){
      t=document.createTextNode(content);
    }
    t.toString = html.toString;
    
    return t;
  },
  getTextInput: function(attr){
    var val,i;
    if(attr!=null && attr['value']){
      val = attr['value'];
    }
    attr['value'] = attr['defaultValue'];
    delete attr['defaultValue'];
    i = this.simpleTag('input', null, attr);
    if(val!=null){
      i.value = val;
    }
    if(i.defaultValue!=""){
      i.size = i.defaultValue.length;
      if(i.value=='' || i.value == i.defaultValue){
        i.value=i.defaultValue;
        i.style.color = "#999";
      }
    }
    
    i.addEventListener("focus" ,function(){if(this.value==this.defaultValue) {this.value = '';this.style.color = '#000';}},false);
    i.addEventListener("blur", function(){if(this.value=='') {this.value = this.defaultValue;this.style.color = '#999';}},false);
    return i;
  },
  img: function(img,attr){
    if(typeof(attr)!='object') attr={};
    attr['src']=Application.images[img];
    if(attr['src']==null) return null;
    return this.simpleTag("img", null, attr);
  },
  button: function(img,linkAttr,imgAttr,assButton){
    var tmp = this.img(img, imgAttr),a;
    if(tmp==null) tmp = img;
    if(assButton){
      a = this.simpleTag("button", tmp, linkAttr);
    }else{
      a = this.simpleTag("a", tmp, linkAttr);
    }
    a.style.cursor = 'pointer';
    return a;
  },
  buttonAndLabel:function(img,label,linkAttr,imgAttr,assButton){
    var a;
    if(assButton){
      a = this.simpleTag('button', null, linkAttr);
    }else{
      a = this.simpleTag("a", null, linkAttr);
    }
    a.style.cursor = 'pointer';
    a.appendChild(this.img(img, imgAttr));
    label = document.createTextNode(label);
    
    a.appendChild(label);
    return a;
  },
  labelAndButton:function(label,img,linkAttr,imgAttr,assButton){
    var a;
    if(assButton){
      a = this.simpleTag('button', null, linkAttr);
    }else{
      a = this.simpleTag("a", null, linkAttr);
    }
    a.style.cursor = 'pointer';
    
    if(typeof(imgAttr) != typeof({})){
      imgAttr={};
    }
    label = document.createTextNode(label);
    
    a.appendChild(label);
    a.appendChild(this.img(img, imgAttr));
    return a;
  },
  arrayIntoTable: function(array,pick,attr){
    var table = this.simpleTag('table', null, attr),i,j,key,tr,tmp,pat;
    if(typeof(array) == 'object' && array.length !=null){
      tr = this.simpleTag('tr');
      if(pick == null || pick.length ==0){
        pick = {};
        for(i in array[0]){
          pick[i] = i;
        }
      }
      for(i in pick){
        tr.appendChild(this.simpleTag('th', i,{"class":'ui-widget-header ui-corner-top'}));
      }
      table.appendChild(tr);
      for(i in array){
        tr = this.simpleTag('tr');
        for(key in pick){
          if(array[i][pick[key]] !== undefined ){
            tr.appendChild(this.simpleTag('td', array[i][pick[key]],{"class":'ui-state-default'}));
          }else{
            tmp =pick[key].toString();
            for(j in array[i]){
              pat  = new RegExp("\\$"+j+"\\$","ig");
              tmp = tmp.toString().replace(pat, array[i][j]);
            }
            pat  = new RegExp("\\$row\\$","ig");
            tmp = tmp.toString().replace(pat, i);
            pat  = new RegExp("\\$row+1\\$","ig");
            tmp = tmp.toString().replace(pat, 1+i*1).replace(/[\n\r]/g, " ");
            try {
              tmp = eval(tmp);
            } catch (exception) { 
              console.log(exception);
            }
            tr.appendChild(this.simpleTag('td', tmp,{"class":'ui-state-default'}));
          }
        }
        
        table.appendChild(tr);
      }
    }
    return table;
  },
  timeEvents:{}
  ,
  menuElement : function(text,attr){
    var $item = html.simpleTag('div', text, attr);
    if(attr ==null){
      attr = {};
    }
    if((window.HTMLElement != null && text instanceof HTMLElement) || (text.nodeType && text.nodeType==1)){
      text = text.innerHTML;
    }
    try{
      if(text instanceof jQuery){
        text = text.html();
      }
    }catch(e){
      
    }
    if(attr['id'] ==null){
      attr['id'] = text;
    }
    try{
      $item.constructor = html.menuElement;
    }catch(exception){
      
    }

    $item.text = attr['id'].replace(/ /g, "_").replace(/\n/g, "").replace(/\r/g, "");
    $item.text = $item.text.toLowerCase();
    //$item.text = str_replace(['ą','ć','ę','ł','ń','ó','ś','ż','ź'],['a','c','e','l','n','o','s','z','z'],$item.text);// 
    $item.items = [];
    $item.submenu_side = "S";
    $item.addItem = function(elem){
      if(typeof(elem)=="object" && elem.constructor == html.menuElement){
        elem.parent = this;
        this.items.push(elem);
        return true;
      }
      return false;
    };
    $item.addEventListener('mouseover', function(e){
      var list,i,viewW,viewH;
      if(!e) e=window.event;
      if(this.items.length > 0){
        e.preventDefault();
        if($("#"+this.text+"_submenu").length==0){
          list = html.simpleTag('span',null,{id:this.text+"_submenu",style:"position:absolute;","class":this.className});
          list.text = this.text;
          list.addEventListener('mouseout', function(){
            if(html.timeEvents[this.text+"_submenu"]!=null){
              window.clearTimeout(html.timeEvents[this.text+"_submenu"]);
            }
            html.timeEvents[this.text+"_submenu"] = window.setTimeout("$('#"+this.text+"_submenu').hide()", 20);
            if(this.parent!=null){
              $(this.parent).mouseout();
            }
          }, false);
          list.addEventListener('mouseover', function(){
            window.clearTimeout(html.timeEvents[this.text+"_submenu"]);
            if(this.parent!=null){
              $(this.parent).mouseover();
            }
          }, false);
          
          for(i in this.items){
            this.items[i].addEventListener('mouseout', function(){
              if(html.timeEvents[this.parent.text+"_submenu"]!=null){
                window.clearTimeout(html.timeEvents[this.parent.text+"_submenu"]);
              }
              html.timeEvents[this.parent.text+"_submenu"] = window.setTimeout("$('#"+this.parent.text+"_submenu').hide()", 20);
              if(this.parent!=null){
                $(this.parent).mouseout();
              }
            }, false);
            this.items[i].addEventListener('mouseover', function(){
              window.clearTimeout(html.timeEvents[this.parent.text+"_submenu"]);
              if(this.parent!=null){
                $(this.parent).mouseover();
              }
            }, false);
            list.appendChild(this.items[i]);
          }
          document.body.appendChild(list);
          
        }
        list = $("#"+this.text+"_submenu")[0];
        //console.log("#"+this.text+"_submenu");
        viewW = document.body.clientWidth;
        viewH = document.body.clientHeight;
        var left=0,top=0;
        $(list).show();
        this.submenu_side = this.submenu_side.toUpperCase();
        left = $(this).offset().left + $(this).outerWidth()/2 - $(list).outerWidth()/2;
        top = $(this).offset().top+$(this).outerHeight()/2 - $(list).outerHeight()/2;
        for(i=0 ; i<this.submenu_side.length; i++){
          switch(this.submenu_side[i]){
            case "N":
              if(i>0){top -= $(list).outerHeight()/2 - $(this).outerHeight()/2 ;}else{top -= $(list).outerHeight()/2 + $(this).outerHeight()/2;}
              break;
            case "E":
              if(i>0){left += $(list).outerWidth()/2 - $(this).outerWidth()/2 ;}else{left += $(list).outerWidth()/2 + $(this).outerWidth()/2;}
              break;
            case "W":
              if(i>0){left -= $(list).outerWidth()/2 - $(this).outerWidth()/2 ;}else{left -= $(list).outerWidth()/2 + $(this).outerWidth()/2;}
              break;
            case "S":
              if(i>0){top += $(list).outerHeight()/2 - $(this).outerHeight()/2 ;}else{top += $(list).outerHeight()/2 +$(this).outerHeight()/2;}
              break;
          }
        }
        list.style.left = left +"px";
        list.style.top = top +"px";
        /*if(this.submenu_side.indexOf("W")>=0){
          left = $(this).offset().left - $(list).outerWidth();
          list.style.left = ($(this).offset().left - $(list).outerWidth()) +"px";
        }else if(this.submenu_side.indexOf("E")>=0){
          left = $(this).offset().left + $(this).outerWidth();
          list.style.left = ($(this).offset().left + $(this).outerWidth()) +"px";
        }else{
          left = $(this).offset().left + $(this).outerWidth()/2 - $(list).outerWidth()/2;
          list.style.left = ($(this).offset().left + $(this).outerWidth()/2 - $(list).outerWidth()/2) +"px";
        }/**/
        if($(list).offset().left - document.body.scrollLeft <0){
          list.style.left = document.body.scrollLeft+"px";
        }
        if($(list).offset().left + $(list).outerWidth() - $(document).scrollLeft()>viewW){
          list.style.left = (viewW - $(list).outerWidth() + $(document).scrollLeft())+"px";
        }

        /*if(this.submenu_side.indexOf("N")>=0){
          list.style.top = ($(this).offset().top - $(list).outerHeight()) +"px";
        }else if(this.submenu_side.indexOf("S")>=0){
          list.style.top = ($(this).offset().top + $(this).outerHeight()) +"px";
        }else{
          list.style.top = ($(this).offset().top)+$(this).outerHeight()/2 - $(list).outerHeight()/2 +"px";
        }/**/
        if($(list).offset().top + $(list).outerHeight() - $(document).scrollTop() > viewH){
          list.style.top = (viewH - $(list).outerHeight() + $(document).scrollTop())+"px";
        }
        if($(list).offset().top - $(document).scrollTop() <0 ){
          list.style.top = $(document).scrollTop()+"px";
        }
      }
    }, false);
    
    $item.addEventListener('mouseout', function(){
      if(html.timeEvents[this.text+"_submenu"]!=null){
        window.clearTimeout(html.timeEvents[this.text+"_submenu"]);
      }
      html.timeEvents[this.text+"_submenu"] = window.setTimeout("$('#"+this.text+"_submenu').hide()", 20);
      if(this.parent!=null){
        $(this.parent).mouseout();
      }
    }, false);
    
    $item.addEventListener('mouseover', function(){
      window.clearTimeout(html.timeEvents[this.text+"_submenu"]);
      if(this.parent!=null){
        $(this.parent).mouseover();
      }
    }, false);
    
    
    return $item;
  },
  validateLiczba: function(ev,elem){
//    if($('#test').length==0){
//      $(document.body).append(tag('span',"",{id:"test"}));
//    }
//    $('#test').html("which: "+ev.which+"<br />keyCode: "+ev.keyCode);
    if(!ev) ev = window.event;
    if(ev.shiftKey || ev.ctrlKey){
      ev.preventDefault();
    }
    if(elem.selectionStart==0 && ev.keyCode==45 && elem.value[0]!="-"){
      return true;
    }
    if(!(ev.which >=48 && ev.which <=57) && ev.which!=8 && ev.keyCode!=46 && ev.which!=46 && !(ev.keyCode >=34 && ev.keyCode <=40)){
      
      ev.preventDefault();
      return false;
    }
    return true;
  },
  validateInput: function(elem){
      var tmp = "",dot=false,i;
      elem.value = elem.value.replace(/,/g,".");
      elem.value = elem.value.replace(/\n/g, "");
      elem.value = elem.value.replace(/\r/g, "");
      elem.value = elem.value.replace(/\t/g, "");
      elem.value = elem.value.replace(/\f/g, "");
      elem.value = elem.value.replace(/ /g, "");
      if(elem.value[0] =="-"){
        tmp = elem.value[0];
      }
      for(i in elem.value){
        if(isFinite(Number(elem.value[i]))){
          tmp += elem.value[i];
        }else if( !dot && elem.value[i]=='.'){
          tmp += elem.value[i];
          dot=true;
        }
      }
      if(tmp=='' || tmp=='.' || tmp=="-"){
        tmp=0;
      }

      elem.value = Number(tmp);
  }

}

$(function(){ // Import GET Vars
   document.$_GET = [];
   var urlHalves = String(document.location).split('?'),urlVars,i,urlVarPair;
   if(urlHalves[1]){
      urlVars = urlHalves[1].split('&');
      for(i=0; i<=(urlVars.length); i++){
         if(urlVars[i]){
            urlVarPair = urlVars[i].split('=');
            document.$_GET[urlVarPair[0]] = urlVarPair[1];
         }
      }
   }
});